package com.cy.jt.security.config.handler;

import com.fasterxml.jackson.databind.ObjectMapper;
import org.springframework.security.access.AccessDeniedException;
import org.springframework.security.web.access.AccessDeniedHandler;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.HashMap;
import java.util.Map;

/**
 * 默认的用于处理访问被拒绝的异常处理器对象
 * 1)Default 默认
 * 2)Access 访问
 * 3)Denied 拒绝
 * 4)Exception 异常
 * 5)Handler 处理器
 */
public class DefaultAccessDeniedExceptionHandler implements AccessDeniedHandler {
    @Override
    public void handle(HttpServletRequest httpServletRequest,
                       HttpServletResponse httpServletResponse,
                       AccessDeniedException e) throws IOException, ServletException {
        //方案1：重定向
       // httpServletResponse.sendRedirect("http://www.tedu.cn");

        //方案2：假如访问被拒绝了，则向客户端响应一个json格式的字符串
        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json;charset=utf-8");
        PrintWriter out = httpServletResponse.getWriter();
        Map<String,Object> map = new HashMap<>();
        map.put("state", 403);
        map.put("message", "没有访问权限，请联系管理员！");

        String js = new ObjectMapper().writeValueAsString(map);
        out.println(js);
        out.flush();
        out.close();
    }
}
